# widgets.py

from django import forms
from django.conf import settings

from django.forms.widgets import flatatt
from django.forms.util import smart_unicode
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse, resolve, NoReverseMatch
from xadmin.ajax.widgets import AjaxInput

        
class BaseAjaxAutoCompleteInput(AjaxInput, forms.Select):
    class Media(AjaxInput.Media):
        js = (
              settings.MEDIA_URL + "xadmin/js/jquery/jquery-1.3.2.min.js",
              settings.MEDIA_URL + "xadmin/js/jquery/jquery.autocomplete.pack.js",
              settings.MEDIA_URL + "xadmin/js/jquery/jquery-ui.1.7.2.min.js",
              )
        css = {
            'all': (settings.MEDIA_URL + "xadmin/css/jquery.autocomplete.css",)
        }
                      
class AjaxLookupInput(BaseAjaxAutoCompleteInput):
    template = 'xadmin/widgets/ajax_lookup_input.html'
    input_type = 'hidden'
    def __init__(self, ajax_service_view, attrs={}):
        self.service_url_name = str(ajax_service_view) 
        self._extrafilters = {}    
        attrs['type'] = 'hidden'
        self.autocomplete_options = {}
        self.autocomplete_options.update( attrs.pop('autocomplete_options', {}) )                
        super(AjaxLookupInput, self).__init__(attrs)
    
#    def _encode(self, d):
#        def subst(k):
#            if k in ('False', False):
#                return 'false'
#            elif k in ('True', True):
#                return 'true'
#            else:
#                return k
#            
#        l = []
#        for k,v in d.items():
#            l.append ( "'%s':%s" % (k,subst(v)) )
#        return "{" + ",\n".join(l) + "}" 
         
    def label_for_value(self, value):
        obj = ""
        if value:
            try:
                service, args, kwargs = resolve( reverse(self.service_url_name) )
                obj = service.queryset.get(pk=value)
            except AttributeError, e:
                raise AttributeError("<Error!! is '%s' url an AjaxService instance ?>" % self.service_url_name, e)
#            except service.queryset.model.DoesNotExist:
#                pass
                #raise Exception( value )
            except NoReverseMatch:
                raise NoReverseMatch( "Cannot reverse '%s'" % self.service_url_name )
            except Exception, e:
                raise e

        return str(obj)
        
    def render(self, name, value=None, attrs=None):
        from django.template.context import Context
        from django.template.loader import get_template
        
        self.choices = [(value, self.label_for_value(value))]
        final_attrs = self.build_attrs(attrs, name=name, type=self.input_type)
        final_attrs['label'] = self.label_for_value(value)
        
                    
        if value and (value!="None"):        
            final_attrs['value'] = escape(smart_unicode(value))
#        else:
#            final_attrs['value'] = ''
        
        p = {'id' :  attrs.get('id'),
             'source': reverse (self.service_url_name) ,
             'options': self.autocomplete_options,
             'attrs' : final_attrs,
             }                        
        t = get_template(self.template)
        return mark_safe( t.render(Context(p)) )


    
            
